package com.opener.common.http;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author baboy
 * @date 09/12/2016
 */
public final class NetworkUtils {
    private static Logger logger = LoggerFactory.getLogger(NetworkUtils.class);
    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
     *
     * @param request
     * @return
     * @throws IOException
     */
    public final static String getIpAddress(HttpServletRequest request)  {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");
        try{
            if (logger.isDebugEnabled()) {
                logger.debug("search_ip|X-Forwarded-For:" + ip);
            }

            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                    if (logger.isDebugEnabled()) {
                        logger.debug("search_ip|Proxy-Client-IP:" + ip);
                    }
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                    if (logger.isDebugEnabled()) {
                        logger.debug("search_ip|WL-Proxy-Client-IP:" + ip);
                    }
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_CLIENT_IP");
                    if (logger.isDebugEnabled()) {
                        logger.debug("search_ip|HTTP_CLIENT_IP:" + ip);
                    }
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                    if (logger.isDebugEnabled()) {
                        logger.debug("search_ip|HTTP_X_FORWARDED_FOR:" + ip);
                    }
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                    if (logger.isDebugEnabled()) {
                        logger.debug("search_ip|remote-addr:" + ip);
                    }
                }
            } else if (ip.length() > 15) {
                String[] ips = ip.split(",");
                for (int index = 0; index < ips.length; index++) {
                    String strIp = (String) ips[index];
                    if (!("unknown".equalsIgnoreCase(strIp))) {
                        ip = strIp;
                        break;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return ip;
    }
    private static boolean isMatch(String regex,String str){
        Pattern p =Pattern.compile(regex,Pattern.MULTILINE);
        Matcher m = p.matcher(str);
        return m.find();
    }
    public static String getBrowserName(String userAgent){
        String IE9 = "MSIE 9.0";
        String IE8 = "MSIE 8.0";
        String IE7 = "MSIE 7.0";
        String IE6 = "MSIE 6.0";
        String MAXTHON = "Maxthon";
        String QQ = "QQBrowser";
        String GREEN="GreenBrowser";
        String SE360="360SE";
        String FIREFOX="Firefox";
        String OPERA="Opera";
        String CHROME="Chrome";
        String SAFARI="Safari";
        String OTHER="App";

        if(isMatch(OPERA, userAgent)){
            return OPERA;
        }
        if(isMatch(CHROME, userAgent)){
            return CHROME;
        }
        if(isMatch(FIREFOX, userAgent)){
            return FIREFOX;
        }
        if(isMatch(SAFARI, userAgent)){
            return SAFARI;
        }
        if(isMatch(SE360, userAgent)){
            return SE360;
        }
        if(isMatch(GREEN,userAgent)){
            return GREEN;
        }
        if(isMatch(QQ,userAgent)){
            return QQ;
        }
        if(isMatch(MAXTHON, userAgent)){
            return MAXTHON;
        }
        if(isMatch(IE9,userAgent)){
            return IE9;
        }
        if(isMatch(IE8,userAgent)){
            return IE8;
        }
        if(isMatch(IE7,userAgent)){
            return IE7;
        }
        if(isMatch(IE6,userAgent)) {
            return IE6;
        }
        return OTHER;
    }
    public static long ipToLong(String ipStr) {
        if(ipStr == null || "".equalsIgnoreCase(ipStr.trim())){
            return 0;
        }
        String[] ipArr = ipStr.split("\\.");
        if(ipArr.length!=4){
            return 0;
        }
        long[] ip = new long[4];
        // 先找到IP地址字符串中.的位置
        // 将每个.之间的字符串转换成整型
        ip[0] = Long.parseLong(ipArr[0]);
        ip[1] = Long.parseLong(ipArr[1]);
        ip[2] = Long.parseLong(ipArr[2]);
        ip[3] = Long.parseLong(ipArr[3]);
        return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
    }

    // 将十进制整数形式转换成127.0.0.1形式的ip地址
    public static String longToIP(long longIp) {
        StringBuffer sb = new StringBuffer("");
        // 直接右移24位
        sb.append(String.valueOf((longIp >>> 24)));
        sb.append(".");
        // 将高8位置0，然后右移16位
        sb.append(String.valueOf((longIp & 0x00FFFFFF) >>> 16));
        sb.append(".");
        // 将高16位置0，然后右移8位
        sb.append(String.valueOf((longIp & 0x0000FFFF) >>> 8));
        sb.append(".");
        // 将高24位置0
        sb.append(String.valueOf((longIp & 0x000000FF)));
        return sb.toString();
    }
}